package com.study.shirotest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

/**
 * @author 陈烨庆
 * @date 2023/4/27
 */
public class ShiroRun {
    public static void main(String[] args) {
        // 1. 初始化获取 SecurityManager
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        // 2. 获取 Subject 对象
        Subject subject = SecurityUtils.getSubject();
        // 3. 创建 token 对象, web应用用户名密码从页面创建
        AuthenticationToken token = new UsernamePasswordToken("zhangsan", "z3");
        // 4. 完成登录
        try {
            subject.login(token);
            System.out.println("登录成功");
            // 5. 判断角色
            boolean hasRole = subject.hasRole("role1");
            System.out.println("是否拥有此角色: " + hasRole);
            // 6. 判断权限
            boolean hasPermitted = subject.isPermitted("user:insert");
            System.out.println("是否拥有此权限: " + hasPermitted);

            // 也可以用 check~,但没返回值, 如果没有会抛出异常
            // subject.checkPermission("user:ins3ert");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("登录失败");
        }
    }
}
